package rate

import (
	"global/constants"
	"github.com/garyburd/redigo/redis"
	"github.com/parnurzeal/gorequest"
	"github.com/ngaut/log"
	"global/core"
	"global/libs/structs"
	"encoding/json"
	"time"
	"global/libs/exchanges"
)

type RateBitZ struct {
	Pool 		*redis.Pool
	Url  		string
	Client 		*gorequest.SuperAgent
	ticker 		*time.Ticker
}

func NewRate(pool *redis.Pool) *RateBitZ {
	return &RateBitZ{
		Pool: 			pool,
		Url: 			constants.BitzHttpBaseUrl,
		Client: 		gorequest.New(),
		ticker: 		time.NewTicker(30 * time.Second),
	}
}

func (r *RateBitZ) getRate()  {
	_, body, errs := r.Client.
		Get(core.GetBitZUrl("currencyRate")).
		Query("symbols=usd_cny,jpy_cny,krw_cny,dkk_cny").
		End()
	if len(errs) > 0 {
		log.Errorf("Error: %s", errs[0])
		return
	}

	type bitzResponse struct {
		exchanges.BitzBaseResponse
		Data 		map[string]structs.CnyRate 		`json:"data"`
	}

	var bitzData bitzResponse
	err := json.Unmarshal([]byte(body), &bitzData)
	if err != nil {
		log.Errorf("Error: %s", err)
		return
	}

	conn := r.Pool.Get()
	defer conn.Close()

	err = core.SaveCnyRate(conn, bitzData.Data)
	if err != nil {
		log.Errorf("Error: %s", err)
	}
}

func (r *RateBitZ) Run() {
	r.getRate()
	go func() {
		for t := range r.ticker.C {
			_ = t
			r.getRate()
		}
	}()
}